#pragma once
#include "log.hpp"
#include "nocpoy.hpp"
#include <cstring>
#include <sys/epoll.h>

class Epoller: public nocopy
{
    const static size_t epoll_size = 128;
private:
    int _epfd;
    int _timeout{3000};  // 3s
    
public:
    Epoller()
    {
        _epfd = epoll_create(epoll_size);
        if (_epfd == -1) {
            LOG(Error, "epoll_create error: %s", strerror(errno));
        }
        else {
            LOG(Info, "epoll_create success, eopll_fd: %d", _epfd);
        }
    }
    ~Epoller()
    {
        if (_epfd > 0) {
            close(_epfd);
        }
    }
    int EpollWait(struct epoll_event revents[], int num)
    {
        int n = epoll_wait(_epfd, revents, num, _timeout);
        return n;
    }
    int EpollUpdate(int oper, int sock, uint32_t event)
    {
        int n = -1;
        if (oper == EPOLL_CTL_DEL) {
            n = epoll_ctl(_epfd, oper, sock, nullptr);
            if (n != 0) {
                LOG(Error, "epoll_ctl delete error!");
            }
        } 
        else {
            // EPOLL_CTL_MOD || EPOLL_CTL_ADD
            struct epoll_event ev;
            ev.data.fd = sock;
            ev.events = event;

            n = epoll_ctl(_epfd, oper, sock, &ev);
            if (n != 0) {
                LOG(Error, "epoll_ctl error!");
            }
        }
        return n;
    }
};